package com.willren.usharejni;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class UshareJni extends Activity {

	private String ifaceName;
	private String ipAddress;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		final Button startButton = (Button) findViewById(R.id.btn_start_server);
		final Button stopButton = (Button) findViewById(R.id.btn_stop_server);

		if (null != startButton) {
			startButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					getIface();

					int retInt = startServer(ifaceName, "", "");
					if (0 == retInt) {
						Toast.makeText(
								UshareJni.this,
								"Server started @ [" + ifaceName + " : "
										+ ipAddress + "]", Toast.LENGTH_SHORT)
								.show();

						startButton.setEnabled(false);
						stopButton.setEnabled(true);
					} else {
						Toast.makeText(UshareJni.this, "error : " + retInt,
								Toast.LENGTH_SHORT).show();
					}
				}
			});
		}

		if (null != stopButton) {
			stopButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					stopServer();

					startButton.setEnabled(true);
					stopButton.setEnabled(false);
				}
			});
		}

		startButton.setEnabled(true);
		stopButton.setEnabled(false);
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		
		stopServer();
	}

	private void getIface() {
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface
					.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf
						.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();

					if (false == inetAddress.isLoopbackAddress()) {
						ifaceName = intf.getName();
						ipAddress = inetAddress.toString();
						break;
					}
				}
			}
		} catch (SocketException ex) {
		}
	}

	public native int startServer(String ifaceName, String serverName,
			String contentDir);

	public native int stopServer();

	static {
		System.loadLibrary("ushare-jni");
	}
}